import json
from pathlib import Path
from typing import List
from CosmeticsRule import CosmeticsRule

class RuleProvider:
    @staticmethod
    def load_rules_from_json(json_path: str) -> List[CosmeticsRule]:
        """从JSON文件加载规则并转换为CosmeticsRule对象列表

        Args:
            json_path (str): JSON文件的路径

        Returns:
            List[CosmeticsRule]: CosmeticsRule对象列表
        """
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
                if not isinstance(data, list):
                    data = [data]
                rules = []
                for item in data:
                    try:
                        rule = CosmeticsRule(
                            id=int(item.get('id', 0)),
                            catalog=str(item.get('catalog', '')),
                            question=str(item.get('question', '')),
                            text=str(item.get('text', ''))
                        )
                        rules.append(rule)
                    except Exception as e:
                        print(f"Error creating rule from item {item}: {str(e)}")
                return rules
        except Exception as e:
            print(f"Error loading rules from {json_path}: {str(e)}")
            return []

    @staticmethod
    def load_all_rules() -> List[CosmeticsRule]:
        """加载data目录下所有JSON文件中的规则

        Returns:
            List[CosmeticsRule]: 所有规则的列表
        """
        data_dir = Path(__file__).parent.parent.parent / 'data'
        rules = []
        
        for json_file in data_dir.glob('*.json'):
            rules.extend(RuleProvider.load_rules_from_json(str(json_file)))
            
        return rules


rp = RuleProvider()
rules = rp.load_rules_from_json("/Users/pc-478/Desktop/private/compliance/data/cm_doc_cosmetics_rule.json")
print(rules)